<template>
  <view class="release">
    <!-- #ifndef MP-TOUTIAO -->
    <singleHeader :pageTitle="$t('videoGoods.add.addTitle')"></singleHeader>
    <!-- #endif -->

    <toolsFile
      v-if="type !== '1'"
      :fileList="pic_list"
      @success="(e) => fileSuccess('pic_list', e)"
      @remove="(i) => pic_list.splice(i, 1)"
    ></toolsFile>
    <view class="fileVideo" v-else>
      <!-- <view class="coverImageTitle">视频</view> -->

      <toolsFile
        fileMediatype="video"
        :fileList="video_url"
        :max="1"
        @success="(e) => fileSuccess('video_url', e)"
        @remove="(i) => video_url.splice(i, 1)"
        @successCover="(e) => fileSuccess('cover_pic', e)"
      ></toolsFile>

      <!-- <view class="coverImageTitle">封面图片</view> -->
      <toolsFile
        :fileList="cover_pic"
        :max="1"
        :fileText="$t('file.cover')"
        @success="(e) => fileSuccess('cover_pic', e)"
        @remove="(i) => cover_pic.splice(i, 1)"
      ></toolsFile>
    </view>

    <view class="inp inp-first">
      <input
        type="text"
        v-model="title"
        :placeholder="$t('videoGoods.add.titlePlaceholder')"
      />
    </view>
    <view class="inp">
      <input type="text" v-model="douyin_url" placeholder="抖音口令" />
    </view>
    <view class="inp border-none">
      <textarea
        v-model="content"
        :maxlength="-1"
        :placeholder="$t('videoGoods.add.textareaPlaceholder')"
      />
    </view>

    <view class="menu" v-if="type === '1'">
      <view class="item" @click="clear">清空</view>
      <view class="item on" @click="showCopy = true">粘贴连接</view>
    </view>

    <view class="selectItem" @click="openPop('1')" v-if="list.length">
      <view class="let">
        <view class="icon"><i class="iconfont icon-Newuserzone"></i></view>
        <view class="text">{{ $t("videoGoods.add.select") }}</view>
      </view>

      <view class="rig">
        <view class="text" v-if="!goods_id.length">
          <!-- {{ $t("videoGoods.add.relevance") }} -->
        </view>
        <view class="text" v-else>
          <image
            mode="aspectFill"
            v-for="item of getMaxCheckImage"
            :src="item.cover_pic"
            :key="item.id"
          >
          </image>
        </view>
        <i class="iconfont icon-arrow-right"></i>
      </view>
    </view>

    <view class="selectItem" @click="openPop('2')">
      <view class="let">
        <view class="icon"><i class="iconfont icon-integral"></i></view>
        <view class="text">{{ $t("videoGoods.add.category") }}</view>
      </view>

      <view class="rig">
        <view class="tag" v-if="catId !== -1">{{
          getCheckedCategoryText
        }}</view>
        <i class="iconfont icon-arrow-right"></i>
      </view>
    </view>

    <view class="selectItem" @click="getPosition">
      <view class="let">
        <view class="icon"><i class="iconfont icon-map-filling1"></i></view>
        <view class="text">{{ $t("shop.place") }}</view>
      </view>

      <view class="rig">
        <view class="tag" v-if="address">{{ address }}</view>
        <i class="iconfont icon-arrow-right"></i>
      </view>
    </view>

    <view class="submit safe-area-inset-bottom" @click="submit">
      <view class="m-btn"> {{ $t("title.issue") }} </view>
    </view>

    <u-popup
      mode="bottom"
      v-model="showPopup"
      :z-index="121"
      border-radius="24"
      safe-area-inset-bottom
      :maskCloseAble="false"
    >
      <view class="popBox">
        <view class="popup-title">
          <view class="let">
            {{ getPopupTitle[0] }}
          </view>

          <i class="iconfont icon-close" @click="showPopup = false"></i>
        </view>
        <view class="inputBox">
          <i class="iconfont icon-search"></i>
          <input
            type="text"
            v-model="text"
            :placeholder="$t('videoGoods.add.keyWord')"
            @confirm="clearList"
          />
        </view>

        <scroll-view
          v-if="selectType === '1'"
          scroll-y
          class="popBoxContent"
          @scrolltolower="scrolltolower"
        >
          <view class="subTit">{{ $t("videoGoods.add.optional") }}</view>
          <goods
            :list="list"
            :isSelect="true"
            :selectList="goods_id"
            @checked="checked"
          ></goods>
        </scroll-view>
        <scroll-view v-else scroll-y class="popBoxContent">
          <category
            :categoryList="categoryList"
            :catId="catId"
            @change="(id) => changeCategory(id)"
          ></category>
        </scroll-view>

        <view
          class="pop-button m-btn safe-area-inset-bottom"
          v-if="selectType === '1'"
          @click="showPopup = false"
        >
          {{ `${$t("list.confirm")}(${goods_id.length})` }}
        </view>
      </view>
    </u-popup>

    <u-popup
      class="popCopy"
      v-model="showCopy"
      :closeable="false"
      mode="center"
      border-radius="24"
    >
      <view class="popCopyCon">
        <view class="title">粘贴连接</view>

        <textarea v-model="url"></textarea>

        <view class="btn">
          <view class="item" @click="showCopy = false">取消</view>
          <view class="item on" @click="getData">获取数据</view>
        </view>
      </view>
    </u-popup>
    <!-- 全局过渡组件 -->
    <transitionPage></transitionPage>
  </view>
</template>

<script>
import videoClassify from "@/api/videoClassify";
import singleHeader from "@/components/diySystemPage/components/singleHeader/index.vue";
import category from "../components/category.vue";
import goods from "../components/goods.vue";
import toolsFile from "@/components/tools/tools-file";

export default {
  components: {
    singleHeader,
    category,
    goods,
    toolsFile
  },

  data() {
    return {
      showPopup: false,
      type: undefined,
      catId: -1,
      title: undefined,
      content: undefined,
      pic_list: [],
      video_url: [],
      list: [], // 商品列表
      categoryList: [],
      goods_id: [],
      selectType: "1", //1.选择商品 2.选择分类
      longitude: undefined,
      latitude: undefined,
      address: "",
      cover_pic: [],
      videoSrc: null,
      text: "",
      page: 1,
      limit: 10,
      isEnd: false,
      showCopy: false,

      url: "",
      oldUrl: "",
      douyin_url: ""
    };
  },

  computed: {
    getPopupTitle() {
      let textArr = [];

      if (this.selectType === "1") {
        textArr[0] = this.$t("videoGoods.add.select");
      } else {
        textArr[0] = this.$t("find.chooseCat");
      }

      return textArr;
    },

    getMaxCheckImage() {
      return this.goods_id.slice(0, 4);
    },

    getCheckedCategoryText() {
      if (this.catId === -1) {
        return;
      }

      let item = this.categoryList.find((el) => el.id === this.catId);
      return item ? item.name : "";
    }
  },

  onShow() {
    let { type, oldUrl, url } = this;
    if (type === "1" && (oldUrl !== url || !oldUrl)) {
      uni.getClipboardData({
        success: (res) => {
          if (res.data) {
            this.showCopy = true;
            this.url = res.data;
            this.oldUrl = res.data;
          }
        }
      });
      return;
    }
  },

  onLoad() {
    this.$utils.hideShareMenu();

    // #ifdef APP-NVUE
    const eventChannel = this.$scope.eventChannel; // 兼容APP-NVUE
    // #endif
    // #ifndef APP-NVUE
    const eventChannel = this.getOpenerEventChannel();
    // #endif

    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on("acceptDataFromOpenedPage", (data) => {
      let { type, categoryList } = data;
      this.type = type;
      this.categoryList = categoryList;
    });

    this.getGoodsList();
  },

  methods: {
    scrolltolower() {
      if (!this.isEnd) {
        this.getGoodsList();
      }
    },

    getGoodsList() {
      let { page, limit, text: name, list: oldList } = this;
      videoClassify
        .videoGoodsGoodsList({
          page,
          limit,
          name
        })
        .then((res) => {
          if (res.code === 0) {
            let { list, row_count: totalCount } = res.data,
              count = parseInt(totalCount);

            if (list.length) {
              oldList.push(...list);
              this.page = page + 1;
            }

            if (oldList.length >= count) {
              this.isEnd = true;
            }
          }
        });
    },

    clearList() {
      this.page = 1;
      this.list = [];
      this.isEnd = false;

      this.getGoodsList();
    },

    remove() {
      // 移除后控制台报错 暂时找不到原因
      this.video_url = [];
    },

    fileSuccess(e, val) {
      this[e].push({
        url: val
      });
    },

    // 选中商品
    checked(item) {
      let { goods_id } = this,
        index = goods_id.findIndex((el) => el.id === item.id);
      if (index === -1) {
        goods_id.push(item);
      } else {
        goods_id.splice(index, 1);
      }
    },

    // 选中分类
    changeCategory(catId) {
      this.catId = catId;
      this.showPopup = false;
    },

    // 打开弹框
    openPop(type) {
      this.selectType = type;
      this.showPopup = true;
    },

    async getPosition() {
      const apiRes = await this.$store.dispatch("getLocation");
      if (apiRes.longitude) {
        uni.chooseLocation({
          success: (res) => {
            this.longitude = String(res.longitude);
            this.latitude = String(res.latitude);
            this.address = res.name;
          },
          fail: () => {
            this.$u.toast(this.$t("my.failPosition"));
          }
        });
      }
    },
    // getAddress(address) {
    //   this.$allrequest.classification
    //     .addressSmart({
    //       address: address,
    //     })
    //     .then((res) => {
    //       if (res.code == 0) {
    //         this.province_id = res.data.province_id;
    //         this.city_id = res.data.city_id;
    //         this.district_id = res.data.region_id;
    //         this.position = res.data.province + res.data.city + res.data.region;
    //       }
    //     });
    // },

    // 提交表单
    submit() {
      let {
        pic_list,
        catId,
        title,
        content,
        type,
        goods_id,
        longitude,
        latitude,
        address,
        video_url,
        cover_pic,
        douyin_url
      } = this;

      if (type === "1") {
        if (!video_url.length) {
          this.$utils.toast("请上传视频！");
          return;
        }

        // #ifdef MP-ALIPAY
        if (!cover_pic.length) {
          this.$utils.toast("请上传视频封面图片！");
          return;
        }
        // #endif
      } else {
        if (!pic_list.length) {
          this.$utils.toast("请上传至少一张图片！");
          return;
        }
      }

      // if (!title) {
      //   this.$utils.toast("标题不能为空！");
      //   return;
      // }

      if (!content) {
        this.$utils.toast("内容不能为空！");
        return;
      }

      if (catId === -1) {
        this.$utils.toast("请选择作品分类！");
        return;
      }

      uni.showLoading({
        title: this.$t("home.loading")
      });

      videoClassify
        .videoGoodsSubmit({
          pic_list: pic_list.map((el) => el.url),
          cat_id: catId,
          title,
          cover_pic:
            type !== "1"
              ? pic_list[0].url
              : cover_pic.length
              ? cover_pic[0].url
              : "",
          content,
          type,
          longitude,
          latitude,
          address,
          goods_id: goods_id.map((el) => el.id),
          video_url: video_url.length
            ? video_url.map((el) => el.url).join(",")
            : undefined,
          douyin_url
        })
        .then((res) => {
          uni.hideLoading();
          if (res.code === 0) {
            this.$utils.showModal("提示", "发布成功！", false, () => {
              uni.navigateBack({
                delta: 1
              });
            });

            return;
          }

          uni.showToast({
            title: res.msg,
            icon: "none"
          });
        })
        .catch((err) => {
          uni.showToast({
            title: err.msg,
            icon: "none"
          });
        });
    },

    clear() {
      this.content = "";
    },

    async getData() {
      let { url } = this;
      if (!url) return this.$utils.toast("链接不能为空！");

      const res = await videoClassify.videoAnalyze(
        {
          url
        },
        true
      );

      if (!res.code) {
        let { title, image, video } = res.data;
        this.title = title;

        this.cover_pic = [{ url: image }];
        this.video_url = [{ url: video }];
        this.showCopy = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.release {
  padding: 0 50rpx 180rpx;
}

.inp-first {
  margin-top: 20rpx;
}

.inp {
  position: relative;
  z-index: 2;
  border-bottom: 1px solid #f2f2f2;
  margin-bottom: 18rpx;

  input,
  textarea {
    font-size: 30rpx;
    color: #333;
    width: 100%;
  }

  input {
    height: 80rpx;
  }

  textarea {
    height: 250rpx;
  }
}

.border-none {
  border-bottom: 0;
}

.selectItem {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 108rpx;
  border-bottom: 1px solid #f2f2f2;
  font-size: 30rpx;

  .let {
    flex: 1;
    display: flex;
    align-items: center;
    overflow: hidden;

    .text {
      color: #262626;
      padding: 0 10rpx;
      flex: 1;
      overflow: hidden;
    }

    .icon {
      width: 38rpx;
      height: 38rpx;
      line-height: 38rpx;
      text-align: center;
      background: #262626;
      border-radius: 120px;
      color: #fff;
    }
  }

  .rig {
    display: flex;
    align-items: center;

    .text {
      color: #8c8c8c;
    }

    image {
      margin-left: 20rpx;
      width: 60rpx;
      height: 60rpx;
    }

    .iconfont {
      margin-left: 10rpx;
      font-size: 18rpx;
      color: #888;
    }

    .tag {
      padding: 8rpx 20rpx;
      background: #f7fafe;
      color: #3d7ac7;
      font-size: 28rpx;
      border-radius: 32px;
      max-width: 400rpx;
      overflow: hidden;
    }
  }

  &:last-of-type {
    border-bottom: 0;
  }
}

/*
  弹框样式 start
*/
.popup-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 0;

  .let {
    font-size: 32rpx;
    color: #262626;
    font-weight: bold;
  }

  .iconfont {
    color: #262626;
  }
}

.popBox {
  display: flex;
  flex-direction: column;
  padding: 0 36rpx;
  height: 70vh;

  .m-btn {
    margin: 10rpx 0;
  }
}

.m-btn {
  height: 80rpx;
  background: #f0250e;
  border-radius: 32px;
  text-align: center;
  color: #fff;
  font-size: 32rpx;
  line-height: 80rpx;
}

.submit {
  position: fixed;
  left: 30rpx;
  right: 30rpx;
  bottom: 10rpx;
}
/*
  弹框样式 end !
*/

.popBoxContent {
  flex: 1;
  overflow-y: auto;
}

.inputBox {
  display: flex;
  align-items: center;
  margin: 10rpx 0;
  padding: 0 24rpx;
  background: #f2f2f2;
  border-radius: 32px;

  .iconfont {
    font-size: 40rpx;
    color: #9b9b9b;
  }

  input {
    flex: 1;
    height: 64rpx;
    line-height: 64rpx;
    font-size: 30rpx;
  }
}

.subTit {
  padding-top: 20rpx;
  font-size: 26rpx;
  color: #333;
}

.videoBox {
  width: 360rpx;
  height: 480rpx;
  background: #d9d9d9;
}

.videoBtn {
  margin-top: 10rpx;
}

.videoBg {
  width: 360rpx;
}

.coverImageTitle {
  padding: 20rpx 0;
  font-size: 30rpx;
  color: #333;
}

::v-deep {
  .uni-checkbox-input {
    border-radius: 50%;
    transform: scale(0.7);
  }

  .uni-checkbox-input-checked {
    border-color: #f0250e !important;
    background: #f0250e;
    color: #fff !important;
  }

  // #ifdef  MP-WEIXIN
  checkbox .wx-checkbox-input {
    border-radius: 50% !important;
    color: #ffffff !important;
    transform: scale(0.7);
  }

  checkbox .wx-checkbox-input.wx-checkbox-input-checked {
    color: #fff;
    background: #f0250e;
    border-color: #f0250e !important;
  }
  // #endif
}

.fileVideo {
  margin: -2rpx;

  ::v-deep {
    .file {
      display: inline-block;
      width: 33.33%;
    }

    .list {
      margin: 0;
    }

    .videoStyle .listBox {
      padding-top: 96%;
    }

    .listItem {
      width: 100% !important;
    }
  }
}

.menu {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;

  .item {
    padding: 0 40rpx;
    margin-left: 16rpx;
    height: 72rpx;
    line-height: 72rpx;
    font-size: 28rpx;
    background: #f2f2f2;
    color: #262626;
    border-radius: 32px;
  }

  .on {
    background: #f0250e;
    color: #fff;
  }
}

.popCopyCon {
  padding: 0 50rpx 50rpx;
  width: 80vw;

  .title {
    padding: 24rpx 0 46rpx;
    font-size: 32rpx;
    color: #262626;
    text-align: center;
    font-weight: bold;
  }

  textarea {
    padding: 24rpx;
    width: 100%;
    height: 240rpx;
    background: #f2f2f2;
    border-radius: 20rpx;
    box-sizing: border-box;
  }

  .btn {
    padding-top: 74rpx;
    display: flex;
    justify-content: space-between;

    .item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 230rpx;
      height: 76rpx;
      border-radius: 32px;
      font-size: 32rpx;
      color: #262626;
      font-weight: bold;
      border: 2rpx solid #999;
    }

    .on {
      background: #f0250e;
      color: #fff;
      border-color: #f0250e;
    }
  }
}
</style>
